package handler

import (
	"net/http"
	"strconv"

	"apiGateWay/internal/config"
	"apiGateWay/pkg/logger"

	"github.com/gin-gonic/gin"
)

// RouteResponse 路由响应结构（带 ID）
type RouteResponse struct {
	ID          string            `json:"id"`
	RouteConfig config.RouteConfig `json:",inline"`
}

// AdminHandler 管理接口处理器
type AdminHandler struct {
	cfg *config.Config
}

// NewAdminHandler 创建管理处理器
func NewAdminHandler(cfg *config.Config) *AdminHandler {
	return &AdminHandler{cfg: cfg}
}

// GetRoutes 获取所有路由
func (h *AdminHandler) GetRoutes(c *gin.Context) {
	routes := make([]RouteResponse, len(h.cfg.Routes))
	for i, route := range h.cfg.Routes {
		routes[i] = RouteResponse{
			ID:          strconv.Itoa(i),
			RouteConfig: route,
		}
	}
	c.JSON(http.StatusOK, routes)
}

// CreateRoute 创建路由
func (h *AdminHandler) CreateRoute(c *gin.Context) {
	var route config.RouteConfig
	if err := c.ShouldBindJSON(&route); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数"})
		return
	}

	// 添加默认值
	if len(route.Methods) == 0 {
		route.Methods = []string{"GET", "POST"}
	}

	// 添加到配置中
	h.cfg.Routes = append(h.cfg.Routes, route)
	id := strconv.Itoa(len(h.cfg.Routes) - 1)
	
	logger.Infof("创建路由: %s -> %s", route.Path, route.Target)
	c.JSON(http.StatusOK, gin.H{
		"message": "路由创建成功",
		"id": id,
		"route": RouteResponse{
			ID:          id,
			RouteConfig: route,
		},
	})
}

// UpdateRoute 更新路由
func (h *AdminHandler) UpdateRoute(c *gin.Context) {
	id := c.Param("id")
	index, err := strconv.Atoi(id)
	if err != nil || index < 0 || index >= len(h.cfg.Routes) {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的路由 ID"})
		return
	}

	var route config.RouteConfig
	if err := c.ShouldBindJSON(&route); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数"})
		return
	}

	h.cfg.Routes[index] = route
	logger.Infof("更新路由 [%d]: %s -> %s", index, route.Path, route.Target)
	c.JSON(http.StatusOK, gin.H{
		"message": "路由更新成功",
		"route": RouteResponse{
			ID:          id,
			RouteConfig: route,
		},
	})
}

// DeleteRoute 删除路由
func (h *AdminHandler) DeleteRoute(c *gin.Context) {
	id := c.Param("id")
	index, err := strconv.Atoi(id)
	if err != nil || index < 0 || index >= len(h.cfg.Routes) {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的路由 ID"})
		return
	}

	deletedRoute := h.cfg.Routes[index]
	h.cfg.Routes = append(h.cfg.Routes[:index], h.cfg.Routes[index+1:]...)
	
	logger.Infof("删除路由: %s -> %s", deletedRoute.Path, deletedRoute.Target)
	c.JSON(http.StatusOK, gin.H{"message": "路由删除成功"})
}

// GetLogs 获取日志
func (h *AdminHandler) GetLogs(c *gin.Context) {
	// TODO: 实现日志查询逻辑
	// 这里返回模拟数据
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "20"))

	c.JSON(http.StatusOK, gin.H{
		"list": []interface{}{},
		"total": 0,
		"page":  page,
		"pageSize": pageSize,
	})
}

// GetAuthConfig 获取认证配置
func (h *AdminHandler) GetAuthConfig(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"jwt": h.cfg.JWT,
		"oauth2": h.cfg.OAuth2,
	})
}

// UpdateAuthConfig 更新认证配置
func (h *AdminHandler) UpdateAuthConfig(c *gin.Context) {
	var req struct {
		JWT    *config.JWTConfig    `json:"jwt"`
		OAuth2 *config.OAuth2Config `json:"oauth2"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数"})
		return
	}

	if req.JWT != nil {
		h.cfg.JWT = *req.JWT
	}
	if req.OAuth2 != nil {
		h.cfg.OAuth2 = *req.OAuth2
	}

	logger.Info("认证配置已更新")
	c.JSON(http.StatusOK, gin.H{"message": "配置更新成功"})
}

// GetRateLimitConfig 获取限流配置
func (h *AdminHandler) GetRateLimitConfig(c *gin.Context) {
	c.JSON(http.StatusOK, h.cfg.RateLimit)
}

// UpdateRateLimitConfig 更新限流配置
func (h *AdminHandler) UpdateRateLimitConfig(c *gin.Context) {
	var rateLimit config.RateLimitConfig
	if err := c.ShouldBindJSON(&rateLimit); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数"})
		return
	}

	h.cfg.RateLimit = rateLimit
	logger.Info("限流配置已更新")
	c.JSON(http.StatusOK, gin.H{"message": "配置更新成功"})
}

// GetSystemConfig 获取系统配置
func (h *AdminHandler) GetSystemConfig(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"server":   h.cfg.Server,
		"cors":     h.cfg.CORS,
		"security": h.cfg.Security,
	})
}

// UpdateSystemConfig 更新系统配置
func (h *AdminHandler) UpdateSystemConfig(c *gin.Context) {
	var req struct {
		Server   *config.ServerConfig   `json:"server"`
		CORS     *config.CORSConfig     `json:"cors"`
		Security *config.SecurityConfig `json:"security"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数"})
		return
	}

	if req.Server != nil {
		h.cfg.Server = *req.Server
	}
	if req.CORS != nil {
		h.cfg.CORS = *req.CORS
	}
	if req.Security != nil {
		h.cfg.Security = *req.Security
	}

	logger.Info("系统配置已更新")
	c.JSON(http.StatusOK, gin.H{"message": "配置更新成功"})
}

// ReloadConfig 重载配置
func (h *AdminHandler) ReloadConfig(c *gin.Context) {
	// TODO: 重新加载配置文件
	logger.Info("配置重载请求")
	c.JSON(http.StatusOK, gin.H{"message": "配置重载成功"})
}

